﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Red.GameData.Raw
{
    partial class DataValue
    {
        /// <summary>
        /// XML shitty parsing code - Load the data value holder from XML node
        /// </summary>
        /// <param name="prop">Parent data property</param>
        /// <param name="log">Error/Progress reporter</param>
        /// <param name="xml">The source XML node</param>
        /// <returns>Loaded object</returns>
        public static DataValue LoadFromNode(DataProperty prop, IGenericFileErrorReporter log, XmlNode xml)
        {
            // get id
            var id = Raw.Utils.AttrID(xml, "id");
            if (id == Guid.Empty)
            {
                // generate new guid (sometimes the value GUIDs may have been omitted)
                // TODO: should this be even allowed ?
                id = Guid.NewGuid();
            }

            // assume that the whole inner stuff inside the XML node is our value
            // NOTE: we trim the whitespace both at the beginning and and the end
            var value = xml.InnerText.Trim();

            // create the value holder
            return new DataValue(prop, id, value);
        }

        /// <summary>
        /// XML shitty saving - Save the data value holder into the XML node
        /// </summary>
        /// <param name="xml">The output XML node</param>
        public void SaveToNode(XmlElement xml)
        {
            Debug.Assert(ID != Guid.Empty); // this is not allowed

            xml.SetAttribute("id", Raw.Utils.FormatValueGuid(ID)); // save the ID
            xml.InnerText = Value;
        }
    }
}
